/**
 * Created by shc on 16/12/20.
 */
var React = require('react');


var Header = require('../widget/Header');
var Brand = require('../widget/Brand');
var TabContent = require('../widget/TabContent');
var Footer = require('../widget/Footer');
var ajax = require('../tools/ajax');
var MD5 = require('../../web/tools/MD5');
var SearchShop = require('./searchShop');

module.exports = React.createClass({
    getInitialState: function () {
        return {
            theme:"Default", //Default/Blue
            topBlock:[],
            middleBlock:[],
            country:"杭州",
            imgList:""
        }
    },
    myScroll:"",

    componentDidMount: function () {
        this.scroll();
        this.init();
        setTimeout(this.swiper,1000);
        setTimeout(this.iscroll,500);
    },
    /**iScroll插件*/
    iscroll(){
        var p =this;
        p.myScroll = new IScroll("#mainWrapper",{
            // 默认iscroll会拦截元素的默认事件处理函数，我们需要响应onClick，因此要配置
            preventDefault: false,
            // 禁止缩放
            zoom: false,
            // 支持鼠标事件，因为我开发是PC鼠标模拟的
            mouseWheel: true,
            // 滚动事件的探测灵敏度，1-3，越高越灵敏，兼容性越好，性能越差
            probeType: 3,
            // 拖拽超过上下界后出现弹射动画效果，用于实现下拉/上拉刷新
            bounce: true,
            // 展示滚动条
            scrollbars: false
        });
        p.myScroll.refresh();
        document.addEventListener('touchmove', function(){}, false);
    },

    init:function () {
        var p = this;
        var shopId = localStorage.getItem("shopId");
        console.log("shopId:"+shopId);
        if(shopId){
            setTimeout(function () {
                p.getBlockByShopId(shopId);
                p.getShopInfoByShopid(shopId);
            },200);
        }else{
            var flag = "null";
            if(window.jsbridge) {
                var time = setInterval(function(){
                    flag = window.jsbridge.getLocationInfo();
                    if (flag != "null") {
                        var gps = JSON.parse(flag);
                        var country = gps.city;
                        if(country != null){
                            localStorage.setItem("country", country);
                            var lat = gps.latitude;
                            var lng = gps.longitude;
                            p.dingwei(lng, lat);
                        }else{
                            p.refs.searchShop.setState({show:true,flag:true});
                        }
                        clearInterval(time);
                    }
                },200);
            }
            if(window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.interOp){
                window.fromIOSLoc=function(gps){
                    if(gps){
                        var loc = gps.split(",");
                        p.dingwei(parseFloat(loc[0]),parseFloat(loc[1]));
                    }else{
                        this.refs.searchShop.setState({show:true,flag:true});
                    }
                };
                var message = {"method":"gps"};
                window.webkit.messageHandlers.interOp.postMessage(message);
                //
            }
            //if(flag == "null"){
            //    this.refs.searchShop.setState({show:true,flag:true});
            //}
        }
    },
    /**定位*/
    dingwei(lng,lat){
        var p =this;
        ajax("POST","dingwei",{},function(dt){
            if(dt&&dt.success){
                var obj = dt.data;
                var min = 0;
                var shopId ="";
                for(var i=0;i<obj.length;i++){
                    if(obj[i].gps) {
                        var gps = obj[i].gps.split(",");
                        var flag = false;
                        var num = Math.sqrt(Math.pow((lng - gps[0]), 2) + Math.pow((lat - gps[1]), 2));
                        min = min == 0 ? num : (num < min ? num : min);
                        if (min == num) {
                            flag = true;
                        }
                        if (flag) {
                            shopId = obj[i].id;
                        }
                    }
                }
                localStorage.setItem("shopId",shopId);
                p.getBlockByShopId(shopId);
                p.getShopInfoByShopid(shopId);
                //setTimeout(p.swiper,1500);
            }
        })
    },
    temp:-1,
    action:function () {
        window.location.reload(true);
    },
    /**根据店铺id获取功能列表*/
    getBlockByShopId:function(id){
        var p = this;
        ajax("POST","getBlockByShopId",{shopid:id},function(dt){
            if(dt && dt.success){
                var objs = dt.data;
                console.log(objs);
                var top = [];
                var middle = [];
                for(var i = 0;i<objs.length;i++){
                    if(objs[i].type==0){
                        top.push(objs[i]);
                    }else{
                        middle.push(objs[i]);
                    }
                }
                p.refs.tabcontent.setState({slist:top});
                p.refs.brand.setState({slist:middle});
            }
        });
    },
    scroll:function(){
        var imgElements = document.getElementsByTagName("img");
        var lazyImgArr = [];
        var aa = [];
        var j = 0;
        for(var i=0; i<imgElements.length; i++) {
            if(imgElements[i].className  == "lazy"){
                lazyImgArr[j++] = imgElements[i];
                aa.push(imgElements[i].alt);
            }
        }
        var scrollHeight = main.scrollTop;//滚动的高度
        var bodyHeight = main.offsetHeight;//body（页面）可见区域的总高度
        if(this.temp < scrollHeight) {//为true表示是向下滚动，否则是向上滚动，不需要执行动作。
            for(var k=0; k<lazyImgArr.length; k++) {
                var imgTop = lazyImgArr[k].offsetTop;//1305（图片纵坐标）
                if((imgTop - scrollHeight) <= bodyHeight) {
                    lazyImgArr[k].src = lazyImgArr[k].alt;
                    lazyImgArr[k].className = "";
                }
            }
            this.temp = scrollHeight;
        }
    },
    /**获取店铺信息*/
    getShopInfoByShopid(shopid){
        var p =this;
        ajax("POST","getShopInfoByShopid",{id:shopid},function(dt){
            if(dt&&dt.success){
                var obj = dt.data[0];
                console.log(obj);
                if(obj){
                    var img = obj.scrollimages.split(',');
                    p.refs.header.setState({shopInfo:obj});
                    if(img[0]){
                        var imgList = img.map(function(obj,index){
                            return(
                                <div key={index} className="swiper-slide">
                                    <img src={obj} />
                                </div>
                            )
                        })
                    }
                    p.setState({imgList:imgList});
                }
                localStorage.setItem("shop_scorllimage",obj.shop_scorllimage);
                localStorage.setItem("url",obj.url);
                localStorage.setItem("discount_img",obj.discount_img);
                localStorage.setItem("new_img",obj.new_img);
                localStorage.setItem("new_scrollimage",obj.new_scrollimage);
            }
        });
    },
    nearby(){
        this.refs.searchShop.setState({show:true});
    },
    /**轮播*/
    swiper(){
        var swiper = new Swiper('.swiper-container', {
            //pagination: '.swiper-pagination',
            grabCursor: true,
            loop:true,
            autoplay:2000,
            effect: 'cube',
            initialSlide :0,
            observer:true,//修改swiper自己或子元素时，自动初始化swiper
            observeParents:true,//修改swiper的父元素时，自动初始化swiper
            cube: {
                shadow: false,
                slideShadows: false,
                shadowOffset: 100,
                shadowScale: 0.94
            }
        });
    },
    render: function () {
        var p =this;
        var shopInfo = localStorage.getItem("shopInfo");
        return (
            <div className="main" id="main">
                <Header ref="header" nearby={p.nearby} theme={p.state.theme} actionType="ewm" icon="#icon-saoyisao" flag={true}></Header>
                <div id="mainWrapper" className="container-t wrap">
                    <div style={{minHeight:"28.66rem"}}>
                        <TabContent nearby={p.nearby} theme={p.state.theme} ref="tabcontent"></TabContent>
                        <div className="swiper">
                            <div className="lunbo" >
                                <div className="bg" style={{width:"95%",height:"12rem",margin:"0 auto",overflow:"hidden"}}>
                                    <div className="swiper-container" style={{height:"12rem"}}>
                                        <div className="swiper-wrapper">
                                            {p.state.imgList}
                                        </div>
                                        <div className="swiper-pagination"></div>
                                    </div>
                                </div>
                                <div className="home-act-msg"  style={{fontSize:"0.6rem",overflow:"hidden",whiteSpace:"pre"}}>
                                    <marquee direction="left"  className="left"  scrollamount="0"  >  <div className="home-bg-dots"></div> <span>新人注册，领红包送大礼！</span></marquee>
                                </div>
                            </div>
                        </div>
                        <Brand theme={p.state.theme} ref="brand"></Brand>
                    </div>
                </div>
                <Footer witchSelected="shouye"></Footer>
                <SearchShop ref="searchShop" action={this.action}/>
            </div>
        )
    }
});
